package com.micro.ai.models.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.models.entity.ModelDefinition;
import com.micro.ai.models.service.ModelDefinitionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 模型定义控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/model-definitions")
@Tag(name = "模型定义管理", description = "模型定义的增删改查")
public class ModelDefinitionController {

    @Autowired
    private ModelDefinitionService modelDefinitionService;

    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:definition:create')")
    @Operation(summary = "创建模型定义", description = "创建新的模型定义")
    public ApiResponse<ModelDefinition> create(@Valid @RequestBody ModelDefinition modelDefinition) {
        log.info("创建模型定义请求: tenantId={}, modelName={}", 
                modelDefinition.getTenantId(), modelDefinition.getModelName());
        modelDefinition.setCreatedBy(getCurrentUsername());
        
        ModelDefinition result = modelDefinitionService.create(modelDefinition);
        return ApiResponse.success("创建成功", result);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:definition:update')")
    @Operation(summary = "更新模型定义", description = "更新模型定义信息")
    public ApiResponse<ModelDefinition> update(
            @Parameter(description = "模型ID", required = true) @PathVariable String id,
            @Valid @RequestBody ModelDefinition modelDefinition) {
        log.info("更新模型定义请求: modelId={}", id);
        
        ModelDefinition result = modelDefinitionService.update(id, modelDefinition);
        return ApiResponse.success("更新成功", result);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasAuthority('model:definition:delete')")
    @Operation(summary = "删除模型定义", description = "删除模型定义")
    public ApiResponse<Void> delete(
            @Parameter(description = "模型ID", required = true) @PathVariable String id) {
        log.info("删除模型定义请求: modelId={}", id);
        
        modelDefinitionService.delete(id);
        return ApiResponse.successVoid("删除成功");
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:definition:view')")
    @Operation(summary = "获取模型定义详情", description = "根据ID获取模型定义详细信息")
    public ApiResponse<ModelDefinition> getById(
            @Parameter(description = "模型ID", required = true) @PathVariable String id) {
        log.info("查询模型定义详情: modelId={}", id);
        
        ModelDefinition modelDefinition = modelDefinitionService.getById(id);
        if (modelDefinition == null) {
            return ApiResponse.error("404", "模型定义不存在");
        }
        
        return ApiResponse.success(modelDefinition);
    }

    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasAuthority('model:definition:view')")
    @Operation(summary = "分页查询模型定义", description = "根据条件分页查询模型定义列表")
    public ApiResponse<Page<ModelDefinition>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "供应商ID") @RequestParam(required = false) String vendorId,
            @Parameter(description = "类型ID") @RequestParam(required = false) String typeId,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        log.info("分页查询模型定义: pageNum={}, pageSize={}", pageNum, pageSize);
        
        Page<ModelDefinition> page = modelDefinitionService.pageQuery(pageNum, pageSize, tenantId, keyword, vendorId, typeId, status);
        return ApiResponse.success(page);
    }

    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null ? authentication.getName() : "system";
    }
}

